package com.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.struts2.ServletActionContext;

import com.entity.Info;
import com.param.Init;
import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;

public class ShowImgAction {
	private String id;
	private InputStream input;
	private String name;
	
	public String show() throws FileNotFoundException{
		//根据id获得文件
		Info info = Init.imgMap.get(id);
		if(info!=null){
			name="attachment;filename="+info.getName();
			File file=new File(Init.imgPath,info.getImgPath());
			InputStream in=new FileInputStream(file);
			ByteOutputStream os=new ByteOutputStream();
			int len=0;
			byte[] bs=new byte[1024];
			try {
				in.read(bs, 0, (int)(Init.decrypt()));
				while((len=in.read(bs))!=-1){
					os.write(bs, 0, len);
				}
				
				input = os.newInputStream();
				
				
			} catch (IOException e) {
				e.printStackTrace();
			}
			finally {
				try {
					if(os!=null){
						os.close();
					}if(in!=null){
						in.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
		}
		
		return "success";
		
	}
	public String list(){
		Map<String, Info> imgMap = Init.imgMap;
		String[] keys=new String[imgMap.size()];
		imgMap.keySet().toArray(keys);
		List<Info> list=new ArrayList<>();
		for(int i=0;i<keys.length;i++){
			list.add(imgMap.get(keys[i]));
		}
		ServletActionContext.getRequest().setAttribute("list", list);
		return "success";
	}
	
	
	
	public InputStream getInput() {
		return input;
	}



	public void setInput(InputStream input) {
		this.input = input;
	}



	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	
	
	
}
